package com.example.asa;

import com.example.asa.Disaster;
import com.example.asa.DisasterDAO;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/historyDisaster")
public class HistoryDisasterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 获取用户角色验证权限
        HttpSession session = request.getSession();
        String role = (String) session.getAttribute("role");

        // 权限检查：仅允许居民查看
        if (role == null || !"resident".equals(role)) {
            request.setAttribute("error", "您没有权限访问此页面");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        // 查询历史灾情数据
        try {
            DisasterDAO disasterDAO = new DisasterDAO();
            List<Disaster> disasterList = disasterDAO.getAllDisasters();

            // 添加调试信息
            System.out.println("查询到的灾情记录数: " + (disasterList != null ? disasterList.size() : "null"));
            if (disasterList != null && !disasterList.isEmpty()) {
                System.out.println("第一条记录: " + disasterList.get(0));
            }

            // 将数据传递给 JSP 页面
            request.setAttribute("disasterList", disasterList);

            // 转发到 JSP 页面显示
            request.getRequestDispatcher("historyDisaster.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            // 更详细的错误信息
            request.setAttribute("error", "加载灾情信息失败：" + e.getClass().getName() + ": " + e.getMessage());
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}